package edu.whu.assignment5.service.impl;

import edu.whu.assignment5.dataobject.User;
import edu.whu.assignment5.repository.UserRepository;
import edu.whu.assignment5.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User findById(int uid) {
        return userRepository.findByUid(uid);
    }

    @Override
    public int registration(User user) {
        User same = userRepository.findByUsername(user.getUsername());
        if(same != null) {
            return -1;  //-1表示有同名的用户，需要重新填写
        }
        User result = userRepository.save(user);
        return result == null ? 0 : 1;
    }

    @Override
    public int login(User user) {
        User exist = userRepository.findByUsername(user.getUsername());
        if(exist == null) {
            return -1; //表示用户不存在
        }
        if(exist.getPassword().equals(user.getPassword())) {
            return 1;
        }
        else {
            return 0;
        }
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public int buyProduct(int uid, int pid) {
        return userRepository.insertUserAndProduct(uid, pid);
    }
}
